package cz.zcu.fav.rat.managed.bean;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import cz.zcu.fav.rat.beans.Indexable;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

public abstract class AbstractTableBean<T extends Indexable, TT> implements
		Serializable
{
	private static final long serialVersionUID = -6973511304665586462L;

	private List<T> filteredObjects;
	private transient ObjectDataModel<T> objectDataModel;
	private List<T> objects;
	private T[] selectedObjects;
	private transient TT service;


	public List<T> getObjects()
	{
		if (objects == null)
		{
			objects = getData();
		}
		return objects;
	}
	
	public ObjectDataModel<T> getObjectDataModel()
	{
		if (objectDataModel == null)
		{
			objectDataModel = new ObjectDataModel<T>(getObjects());
		}
		return objectDataModel;
	}

	public T[] getSelectedObjects()
	{
		return selectedObjects;
	}

	public void setSelectedObjects(T[] selectedObjects)
	{
		this.selectedObjects = selectedObjects;
	}

	public List<T> getFilteredObjects()
	{
		return filteredObjects;
	}

	public void setFilteredObjects(List<T> filteredObjects)
	{
		this.filteredObjects = filteredObjects;
	}

	public void deleteSelectedObjects()
	{
		if (selectedObjects == null || selectedObjects.length == 0)
		{
			notifyNoItemSelected();
			return;
		}

		performDelete(Arrays.asList(selectedObjects));
		objects = getData();
		objectDataModel = null;
		String message = LocaleMessageFactory
				.getLocale("view.objectsearch.info.objectsdeleted");

		FacesContext.getCurrentInstance().addMessage("form",
				new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));

	}

	protected abstract TT getService();

	protected TT getDataProvider()
	{
		if (service == null)
		{
			service = getService();
		}
		return service;
	}

	protected abstract void performDelete(List<T> objects);

	protected void notifyNoItemSelected()
	{
		String message = LocaleMessageFactory
				.getLocale("view.objectsearch.warn.objectsnotselected");

		FacesContext.getCurrentInstance().addMessage("form",
				new FacesMessage(FacesMessage.SEVERITY_WARN, message, message));
	}

	protected abstract List<T> getData();

}
